package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Category;
import com.itheima.bean.Dish;
import com.itheima.bean.Setmeal;
import com.itheima.common.PageParam;
import com.itheima.dao.CategoryDao;
import com.itheima.dto.DishDto;
import com.itheima.exception.CustomException;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.logging.LogManager;

/**
 * @Author: LiuBanXian
 * @Date: 2022/9/4  14:37
 * @description:
 */
@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 分类管理::添加分类 | 套餐
     *
     * @param category
     * @return
     */
    @Override
    public int add(Category category) {
        return categoryDao.insert(category);
    }

    /**
     * 分类管理::分页展示
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<Category> findPage(PageParam pageParam) {
        IPage<Category> page = new Page<>(pageParam.getPage(), pageParam.getPageSize());
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        return categoryDao.selectPage(page, lqw);
    }

    /**
     * 分类管理删除
     *
     * @param id
     * @return
     */
    @Override
    public int delete(long id) {
        //查询菜品表
        List<DishDto> dishiList = dishService.findByCategoryId(id,null);
        if (dishiList.size() > 0) {
            throw new CustomException("当前分类下还有未下架的商品,禁止删除");
        }
        //查询套餐表
        List<Setmeal> setmealList = setmealService.findByCategoryId(id);
        if (setmealList.size() > 0) {
            throw new CustomException("当前分类下还有未下架的商品,禁止删除");
        }
        return categoryDao.deleteById(id);
    }

    /**
     * 修改信息
     *
     * @param category
     * @return
     */
    @Override
    public int update(Category category) {
       return categoryDao.updateById(category);
    }

    @Override
    public List<Category> findByType(Integer type) {
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();

        //设置条件 如果不为空就追加 条件  为空就不用追加条件 就查询所有的
        lqw.eq(type!=null,Category::getType,type);

        return categoryDao.selectList(lqw);
    }

    @Override
    public Category findById(Long categoryId) {
        return categoryDao.selectById(categoryId);
    }


}
